package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Api(tags = "文章接口")
@RequestMapping("/article")
@RestController
public class ArticleController {

    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布新帖子
     * @param request
     * @param boardId 版块Id
     * @param title  文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                       @ApiParam("板块id")@RequestParam("boardId") Long boardId,
                       @ApiParam("文章标题")@RequestParam("title") String title,
                       @ApiParam("文章内容")@RequestParam("content") String content) {
        //校验用户禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //板块校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        //调用Service
        articleService.create(article);
        return AppResult.success();
    }
    @ApiOperation("获取帖子列表")
    @GetMapping("getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("版块id")@RequestParam(value = "boardId",required = false) Long boardId) {
        List<Article> articles;
        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if (articles == null) {
            articles = new ArrayList<>();
        }

        //响应结果
        return AppResult.success(articles);
    }
    @ApiOperation("根据用户id查询所有帖子")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> selectByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id")@RequestParam(value = "userId",required = false) Long userId) {
        //如果用户id为空，从当前登录用户的session中获取user对象
        if (userId == null ) {
            //获取session
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);


        return AppResult.success(articles);
    }
    @ApiOperation("根据帖子id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,@ApiParam("帖子id")@RequestParam("id") @NonNull Long id) {
        //从Session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);


        Article article = articleService.selectDetailById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断是否为作者
        if (user.getId().equals(article.getUserId())) {
            article.setOwn(true);
        }
        System.out.println(article);
        return AppResult.success(article);
    }
    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id")@RequestParam("id")@NonNull Long id,
                            @ApiParam("帖子标题")@RequestParam("title")@NonNull String title,
                            @ApiParam("帖子内容")@RequestParam("content")@NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1 ) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //判断帖子状态 ——已归档
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用Service
        articleService.modify(id,title,content);
        log.info("帖子更新成功。 Article id = " + id + "User id = " + user.getId() + " .");


        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUpById")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam("帖子id")@RequestParam("id") Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState() == 1 ) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用Service
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id")@RequestParam("id") Long id) {
        //判断用户的登录状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if (user.getState() == 1 ) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //校验帖子的状态
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验用户是否为作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service
        articleService.deleteById(id);

        //返回结果
        return AppResult.success();
    }
}
